/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Food;
import java.util.ArrayList;
import java.util.Collection;
import pojo.Ingredient;

/**
 *
 * @author A7med Kotb
 */
public class IngredientJpaController implements Serializable {

    public IngredientJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Ingredient ingredient) throws RollbackFailureException, Exception {
        if (ingredient.getFoodCollection() == null) {
            ingredient.setFoodCollection(new ArrayList<Food>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Food> attachedFoodCollection = new ArrayList<Food>();
            for (Food foodCollectionFoodToAttach : ingredient.getFoodCollection()) {
                foodCollectionFoodToAttach = em.getReference(foodCollectionFoodToAttach.getClass(), foodCollectionFoodToAttach.getId());
                attachedFoodCollection.add(foodCollectionFoodToAttach);
            }
            ingredient.setFoodCollection(attachedFoodCollection);
            em.persist(ingredient);
            for (Food foodCollectionFood : ingredient.getFoodCollection()) {
                foodCollectionFood.getIngredientCollection().add(ingredient);
                foodCollectionFood = em.merge(foodCollectionFood);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Ingredient ingredient) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Ingredient persistentIngredient = em.find(Ingredient.class, ingredient.getId());
            Collection<Food> foodCollectionOld = persistentIngredient.getFoodCollection();
            Collection<Food> foodCollectionNew = ingredient.getFoodCollection();
            Collection<Food> attachedFoodCollectionNew = new ArrayList<Food>();
            for (Food foodCollectionNewFoodToAttach : foodCollectionNew) {
                foodCollectionNewFoodToAttach = em.getReference(foodCollectionNewFoodToAttach.getClass(), foodCollectionNewFoodToAttach.getId());
                attachedFoodCollectionNew.add(foodCollectionNewFoodToAttach);
            }
            foodCollectionNew = attachedFoodCollectionNew;
            ingredient.setFoodCollection(foodCollectionNew);
            ingredient = em.merge(ingredient);
            for (Food foodCollectionOldFood : foodCollectionOld) {
                if (!foodCollectionNew.contains(foodCollectionOldFood)) {
                    foodCollectionOldFood.getIngredientCollection().remove(ingredient);
                    foodCollectionOldFood = em.merge(foodCollectionOldFood);
                }
            }
            for (Food foodCollectionNewFood : foodCollectionNew) {
                if (!foodCollectionOld.contains(foodCollectionNewFood)) {
                    foodCollectionNewFood.getIngredientCollection().add(ingredient);
                    foodCollectionNewFood = em.merge(foodCollectionNewFood);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = ingredient.getId();
                if (findIngredient(id) == null) {
                    throw new NonexistentEntityException("The ingredient with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Ingredient ingredient;
            try {
                ingredient = em.getReference(Ingredient.class, id);
                ingredient.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The ingredient with id " + id + " no longer exists.", enfe);
            }
            Collection<Food> foodCollection = ingredient.getFoodCollection();
            for (Food foodCollectionFood : foodCollection) {
                foodCollectionFood.getIngredientCollection().remove(ingredient);
                foodCollectionFood = em.merge(foodCollectionFood);
            }
            em.remove(ingredient);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Ingredient> findIngredientEntities() {
        return findIngredientEntities(true, -1, -1);
    }

    public List<Ingredient> findIngredientEntities(int maxResults, int firstResult) {
        return findIngredientEntities(false, maxResults, firstResult);
    }

    private List<Ingredient> findIngredientEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Ingredient.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Ingredient findIngredient(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Ingredient.class, id);
        } finally {
            em.close();
        }
    }

    public int getIngredientCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Ingredient> rt = cq.from(Ingredient.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
